package com.htjy.baselibrary.library_appmanage;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.text.TextUtils;

import java.util.List;

/**
 * Created by besttimer on 2022/1/21
 */
public class ActivityUtils {

    public static void goAndCleanHistory(Context context, Class<?> cls) {
        Intent intent = new Intent(context, cls);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        context.startActivity(intent);
    }

    /**
     * 是否需要拦截处理
     */
    public static boolean isNeedHandle(Activity activity) {
        return !TextUtils.equals(getLauncherActivity(activity.getApplication()), activity.getClass().getName()) && AppUtils.isFromRestore();
    }

    /**
     * 标志这是正常使用流程，在onResume调用
     */
    public static void markSplash(Activity activity) {
        if (TextUtils.equals(getLauncherActivity(activity.getApplication()), activity.getClass().getName())) {
            AppUtils.setFromRestore(false);
        }
    }

    public static String getLauncherActivity(Application application) {
        return getLauncherActivity(application, application.getPackageName());
    }

    public static String getLauncherActivity(Application application, final String pkg) {
        Intent intent = new Intent(Intent.ACTION_MAIN, null);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setPackage(pkg);
        PackageManager pm = application.getPackageManager();
        List<ResolveInfo> info = pm.queryIntentActivities(intent, 0);
        ResolveInfo next = info.iterator().next();
        if (next != null) {
            return next.activityInfo.name;
        }
        return "no launcher activity of " + pkg;
    }

}
